//
//  DXWADViewController.m
//  BuDeJie
//
//  Created by 淡馨慰 on 16/7/29.
//  Copyright © 2016年 淡馨慰. All rights reserved.
//

#import "DXWADViewController.h"
#import "AFHTTPSessionManager+DXWManager.h"
#import "DXWAdItem.h"
#import <MJExtension/MJExtension.h>
#import <SDWebImage/UIImageView+WebCache.h>
#import "DXWTabBarController.h"


#define DXWcode2 @"phcqnauGuHYkFMRquANhmgN_IauBThfqmgKsUARhIWdGULPxnz3vndtkQW08nau_I1Y1P1Rhmhwz5Hb8nBuL5HDknWRhTA_qmvqVQhGGUhI_py4MQhF1TvChmgKY5H6hmyPW5RFRHzuET1dGULnhuAN85HchUy7s5HDhIywGujY3P1n3mWb1PvDLnvF-Pyf4mHR4nyRvmWPBmhwBPjcLPyfsPHT3uWm4FMPLpHYkFh7sTA-b5yRzPj6sPvRdFhPdTWYsFMKzuykEmyfqnauGuAu95Rnsnbfknbm1QHnkwW6VPjujnBdKfWD1QHnsnbRsnHwKfYwAwiu9mLfqHbD_H70hTv6qnHn1PauVmynqnjclnj0lnj0lnj0lnj0lnj0hThYqniuVujYkFhkC5HRvnB3dFh7spyfqnW0srj64nBu9TjYsFMub5HDhTZFEujdzTLK_mgPCFMP85Rnsnbfknbm1QHnkwW6VPjujnBdKfWD1QHnsnbRsnHwKfYwAwiuBnHfdnjD4rjnvPWYkFh7sTZu-TWY1QW68nBuWUHYdnHchIAYqPHDzFhqsmyPGIZbqniuYThuYTjd1uAVxnz3vnzu9IjYzFh6qP1RsFMws5y-fpAq8uHT_nBuYmycqnau1IjYkPjRsnHb3n1mvnHDkQWD4niuVmybqniu1uy3qwD-HQDFKHakHHNn_HR7fQ7uDQ7PcHzkHiR3_RYqNQD7jfzkPiRn_wdKHQDP5HikPfRb_fNc_NbwPQDdRHzkDiNchTvwW5HnvPj0zQWndnHRvnBsdPWb4ri3kPW0kPHmhmLnqPH6LP1ndm1-WPyDvnHKBrAw9nju9PHIhmH9WmH6zrjRhTv7_5iu85HDhTvd15HDhTLTqP1RsFh4ETjYYPW0sPzuVuyYqn1mYnjc8nWbvrjTdQjRvrHb4QWDvnjDdPBuk5yRzPj6sPvRdgvPsTBu_my4bTvP9TARqnam"

#define DXWAdURL @"http://mobads.baidu.com/cpro/ui/mads.php"


@interface DXWADViewController ()

@property (weak, nonatomic) IBOutlet UIImageView *launchImageView;

@property (weak, nonatomic) IBOutlet UIView *adView;

@property (weak, nonatomic) IBOutlet UIButton *jumpBtn;
/** GCD定时器 */
//@property (nonatomic, strong) dispatch_source_t timer;
/** NSTimer定时器 */
@property (nonatomic, strong) NSTimer *timer;

/** 广告模型 */
@property (nonatomic, strong) DXWAdItem *item;

@end

@implementation DXWADViewController


-(void)dealloc
{
    NSLog(@"%s",__func__);
}
- (IBAction)jumpBtnClick:(id)sender
{
//    NSLog(@"点击了跳过按钮");
    DXWTabBarController *tabBarVC = [[DXWTabBarController alloc]init];
    [[UIApplication sharedApplication].keyWindow setRootViewController:tabBarVC];
    NSLog(@"跳转成功");
    [self.timer invalidate];
    NSLog(@"关闭定时器");
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //1. 进行屏幕适配
    [self setupLaunchImage];
    
    //2. 加载网络数据
    [self loadWebDatas];

    /**
     * 3. 添加定时器 -- 跳过按钮的设置
     */
    /* ------方式一:GCD-----------
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(timer, ^{
        static int i = 4;
        i--;
        NSLog(@"%d",i);
        self.jumpBtn.titleLabel.text = [NSString stringWithFormat:@"跳过(%d)",i];
        if (i <= 0) {

            DXWTabBarController *tabBarVC = [[DXWTabBarController alloc]init];
            [[UIApplication sharedApplication].keyWindow setRootViewController:tabBarVC];
            NSLog(@"跳转成功");
            dispatch_cancel(timer);
            dispatch_source_cancel(timer);
            NSLog(@"关闭定时器");
            
        }
    });
    dispatch_resume(timer);
    self.timer = timer;
                --------------------*/
    // -------方式二:NSTimer----------
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(jumpTabBarVC) userInfo:nil repeats:YES];
    self.timer = timer;
    
     
     
    

    
}
- (void)jumpTabBarVC
{
    static int i = 4;
    i--;
    NSLog(@"%d",i);
    self.jumpBtn.titleLabel.text = [NSString stringWithFormat:@"跳过(%d)",i];
    if (i < 0) {
        //相当于点击跳过按钮
        [self jumpBtnClick:nil];
    }
}
//3. 点击广告图片跳转url
- (void)adImageClick
{
    NSLog(@"点击了广告界面");
    UIApplication *app = [UIApplication sharedApplication];
    //广告图片点击跳转的url
    NSURL *url = [NSURL URLWithString:self.item.winurl];
    //先判断是否可以打开url
    if ([app canOpenURL:url]) {
        [app openURL:url];
    }
  
}

//2. 加载网络数据
- (void)loadWebDatas
{
    //显示广告图片 ==> 找服务器获取数据 ==> 查看接口文档 ==> 验证接口(在浏览器输入完整url) ==> 使用AFN加载数据
    
    //1. 创建会话请求对象 --- 自定义请求对象 允许接收text/html
    AFHTTPSessionManager *manager = [AFHTTPSessionManager dxw_Manager];
    
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    //2. 完整的url = 请求url + 请求参数
    //请求url @"http://mobads.baidu.com/cpro/ui/mads.php"
    //请求参数 code2
    //请求失败:响应体既不是JSON也不是XML
    
    NSDictionary *dict = @{
                           @"code2" : DXWcode2
                           };
    
    [manager GET:DXWAdURL parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
//        NSLog(@"%@",responseObject); //修改AFN
        
        //4. 只接受字典的第一个 ad 数组
        NSDictionary *dict = [responseObject[@"ad"] firstObject];
        DXWAdItem *item = [DXWAdItem mj_objectWithKeyValues:dict];
        self.item = item;
        
        //5. 根据模型数据设置广告界面
        
        //5.1 计算图片高度
        CGFloat adHeight =  screenW / item.w * item.h ;
        UIImageView *adImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, screenW, adHeight)];
        adImageView.userInteractionEnabled = YES;
        
        //5.2 使用SDW框架加载广告图片
        NSURL *adURL = [NSURL URLWithString:item.w_picurl];
        [adImageView sd_setImageWithURL:adURL];
        [self.adView addSubview:adImageView];
        
        //5.3 给图片添加点击手势
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(adImageClick)];
        [adImageView addGestureRecognizer:tapGesture];
        
        

        
        //3.将解析后的数据写入plist文件
//        [responseObject writeToFile:@"/Users/milkteacat/Desktop/淡/dxw大神班17期-2/0727项目/代码--广告界面/ad.plist" atomically:YES];

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
    
    
}
//1. 进行屏幕适配
- (void)setupLaunchImage
{
//    NSLog(@"%f",[UIScreen mainScreen].bounds.size.height) ;
    
    /**
     *  打印出来的浮点型,可以强制转换成整型
     */
    
    if (iPhone6P) {
        self.launchImageView.image = [UIImage imageNamed:@"LaunchImage-800-Portrait-736h@3x"];
    }
    else if (iPhone6)
    {
        self.launchImageView.image = [UIImage imageNamed:@"LaunchImage-800-667h"];
    }
    else if (iPhone5)
    {
        self.launchImageView.image = [UIImage imageNamed:@"LaunchImage-700-568h"];
    }
    else
        self.launchImageView.image = [UIImage imageNamed:@"LaunchImage-700"];}



@end
